<?php

namespace app\admin\model\order;

use app\common\enum\order\PayType as PayTypeEnum;
use app\common\model\Order as OrderModel;
use app\common\model\store\shop\Order as ShopOrder;
use app\common\service\Order as OrderService;
use app\common\service\order\Complete as OrderCompleteService;
use app\store\model\User as UserModel;
use app\store\model\UserCoupon as UserCouponModel;
use app\store\service\order\Export as Exportservice;
use app\common\library\helper;
use app\common\enum\OrderType as OrderTypeEnum;
use app\common\enum\DeliveryType as DeliveryTypeEnum;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\service\wechat\wow\Order as WowService;
use app\common\service\goods\source\Factory as FactoryStock;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\Status as OrderStatusEnum;
use think\Model;

/**
 * 订单管理
 * Class Order
 * @package app\store\model
 */
class Order extends Model
{


    protected $name = 'order';
    protected $alias = 'order';

    /**
     * 订单状态文字描述
     * @param $value
     * @param $data
     * @return string
     */
    public function getStateTextAttr($value, $data)
    {
        // 订单状态
        if (in_array($data['order_status'], [20, 30])) {
            $orderStatus = [20 => '已取消', 30 => '已完成'];
            return $orderStatus[$data['order_status']];
        }
        // 付款状态
        if ($data['pay_status'] == 10) {
            return '待付款';
        }
        // 订单类型：单独购买
        if ($data['delivery_status'] == 10) {
            return '已付款，待发货';
        }
        if ($data['receipt_status'] == 10) {
            return '已发货，待收货';
        }
        return $value;
    }
    public static function getPaylist(){
        return  [ 10 => '余额支付', 20 => '微信支付'];

    }

    public static function getPayStatusList(){
        return  [ 10 => '未付款', 20 => '已付款'];
    }

    /**
     * 获取器：订单金额(含优惠折扣)
     * @param $value
     * @param $data
     * @return string
     */
    public function getOrderPriceAttr($value, $data)
    {
        // 兼容旧数据：订单金额
        if ($value == 0) {
            return helper::bcadd(helper::bcsub($data['total_price'], $data['coupon_money']), $data['update_price']);
        }
        return $value;
    }

    /**
     * 改价金额（差价）
     * @param $value
     * @return array
     */
    public function getUpdatePriceAttr($value)
    {
        return [
            'symbol' => $value < 0 ? '-' : '+',
            'value' => sprintf('%.2f', abs($value))
        ];
    }

    /**
     * 付款状态
     * @param $value
     * @return array
     */
    public function getPayTypeAttr($value)
    {
        return ['text' => PayTypeEnum::data()[$value]['name'], 'value' => $value];
    }



    /**
     * 订单类型
     * @param $value
     * @return array
     */
    public function getOrderSourceAttr111($value)
    {
        $status = [10 => '普通订单', 20 => '砍价订单', 30 => '秒杀订单', 40 => '储值卡订单', 50 => '当面付订单'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 付款状态
     * @param $value
     * @return array
     */
    public function getPayStatusAttr($value)
    {
        return ['text' => PayStatusEnum::data()[$value]['name'], 'value' => $value];
    }

    /**
     * 发货状态
     * @param $value
     * @return array
     */
    public function getDeliveryStatusAttr($value)
    {
        $status = [10 => '待发货', 20 => '已发货'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 收货状态
     * @param $value
     * @return array
     */
    public function getReceiptStatusAttr($value)
    {
        $status = [10 => '待收货', 20 => '已收货'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 收货状态
     * @param $value
     * @return array
     */
    public function getOrderStatusAttr($value)
    {
        $status = [10 => '进行中', 20 => '已取消', 21 => '待取消', 30 => '已完成'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 配送方式
     * @param $value
     * @return array
     */
    public function getDeliveryTypeAttr($value)
    {
        return ['text' => DeliveryTypeEnum::data()[$value]['name'], 'value' => $value];
    }
    /**
     * 订单商品列表
     * @return \think\model\relation\HasMany
     */
    public function goods()
    {

        return $this->hasMany("app\common\model\OrderGoods");
    }

    /**
     * 关联订单收货地址表
     * @return \think\model\relation\HasOne
     */
    public function address()
    {

        return $this->hasOne("app\common\model\OrderAddress");
    }

    /**
     * 关联订单收货地址表
     * @return \think\model\relation\HasOne
     */
    public function extract()
    {

        return $this->hasOne("app\common\model\OrderExtract");
    }

    /**
     * 关联自提门店表
     * @return \think\model\relation\BelongsTo
     */
    public function extractShop()
    {

        return $this->belongsTo("app\common\model\store\Shop", 'extract_shop_id');
    }

    /**
     * 关联门店店员表
     * @return \think\model\relation\BelongsTo
     */
    public function extractClerk()
    {

        return $this->belongsTo("app\common\model\store\shop\Clerk", 'extract_clerk_id');
    }

    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {

        return $this->belongsTo("app\common\model\User");
    }
    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function wxapp()
    {

        return $this->belongsTo("app\common\model\Wxapp",'wxapp_id','wxapp_id');
    }

    /**
     * 关联物流公司表
     * @return \think\model\relation\BelongsTo
     */
    public function express()
    {

        return $this->belongsTo("app\common\model\Express");
    }







    /**
     * 订单详情
     * @param array|int $where
     * @param array $with
     * @return null|\app\common\model\Order
     * @throws \think\exception\DbException
     */
    public static function detail($where, $with = [
        'user',
        'address',
        'goods' => ['image'],
        'extract',
        'express',
        'extract_shop.logo',
        'extract_clerk'
    ])
    {
        is_array($where) ? $filter = $where : $filter['order_id'] = (int)$where;

        return self::get($filter, $with);
    }





    /**
     * 订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($query = [])
    {
        // 检索查询条件
       !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image','wxapp',  'address', 'user'])
            ->alias('order')
            ->field('order.*')
            ->join('wxapp', 'wxapp.wxapp_id = order.wxapp_id')
            ->join('user', 'user.user_id = order.user_id')
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc','order.order_id' => 'desc'])
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 订单列表(全部)
     * @param $dataType
     * @param array $query
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getListAll( $query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user', 'extract', 'extract_shop'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->select();
    }

    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList( $query)
    {
        // 获取订单列表
        $list = $this->getListAll( $query);
        // 导出csv文件
        return (new Exportservice)->orderList($list);
    }



    /**
     * 设置检索查询条件
     * @param $query
     */
    private function setWhere($query)
    {
        if (isset($query['search']) && !empty($query['search'])) {
            $this->where('wxapp.wxapp_name|order.order_no|user.nickName', 'like', '%' . trim($query['search']) . '%');
        }

//        if (isset($query['start_time']) && !empty($query['start_time'])) {
//            $this->where('order.create_time', '>=', strtotime($query['start_time']));
//        }
//        if (isset($query['end_time']) && !empty($query['end_time'])) {
//            $this->where('order.create_time', '<', strtotime($query['end_time']) + 86400);
//        }

        if (isset($query['search_time']) && !empty($query['search_time'])) {
            $times=explode('至',$query['search_time']);
            $this->where('order.create_time','between time',$times);
        }
        if (isset($query['pay_type']) && !empty($query['pay_type'])){
            $query['pay_type'] > -1 && $this->where('order.pay_type', '=', $query['pay_type']);
        }
        if (isset($query['pay_status']) && !empty($query['pay_status'])){
            $query['pay_status'] > -1 && $this->where('order.pay_status', '=', $query['pay_status']);
        }
        if (isset($query['delivery_type']) && !empty($query['delivery_type'])) {
            $query['delivery_type'] > -1 && $this->where('delivery_type', '=', $query['delivery_type']);
        }
        if (isset($query['extract_shop_id']) && !empty($query['extract_shop_id'])) {
            $query['extract_shop_id'] > -1 && $this->where('extract_shop_id', '=', $query['extract_shop_id']);
        }
        // 用户id
        if (isset($query['user_id']) && $query['user_id'] > 0) {
            $this->where('order.user_id', '=', (int)$query['user_id']);
        }
    }








}
